package com.lagou.web;

import com.lagou.domain.User;
import com.lagou.service.UserService;
import com.lagou.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

public class LoginServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 解决中文乱码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        //获取登录用户名
        String username = req.getParameter("username");
        //获取登录密码
        String password = req.getParameter("password");
        System.out.println("username:" + username + ",password:" + password);

        //创建userService对象,接口接收
        UserService userService = new UserServiceImpl();
        //调用Service方法，根据提交过来的用户名和密码进行数据查询
        try {
            User user = userService.login(username,password);
            if (user != null){
                HttpSession session = req.getSession();
                session.setAttribute("user",user);
                resp.sendRedirect("success.html");
            }else{
                resp.getWriter().println("用户名或密码错误！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
